package cc.mrbird.febs.buss.controller;

import cc.mrbird.febs.buss.entity.MenuItemFile;
import cc.mrbird.febs.buss.entity.TFile;
import cc.mrbird.febs.buss.service.IMenuItemFileService;
import cc.mrbird.febs.buss.service.ITFileService;
import cc.mrbird.febs.buss.util.ConfigResourceUtil;
import cc.mrbird.febs.buss.util.ConvertUtil;
import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.common.utils.FebsUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.*;

/**
 *  Controller
 *
 * @author Lujingyuan
 * @date 2020-02-27 18:08:45
 */
@Slf4j
@Validated
@Controller
public class TFileController extends BaseController {

    @Autowired
    private ITFileService tFileService;
    @Autowired
    private IMenuItemFileService itemFileService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "tFile")
    public String tFileIndex(){
        return FebsUtil.view("tFile/tFile");
    }

    @GetMapping("file")
    @ResponseBody
    @RequiresPermissions("tFile:list")
    public FebsResponse getAllTFiles(TFile tFile) {
        System.out.println("-start--");
        System.out.println(ConfigResourceUtil.getConfigByName("abc"));
        System.out.println("-end--");
        return new FebsResponse().success().data(tFileService.findTFiles(tFile));
    }

    @GetMapping("file/list")
    @ResponseBody
    public FebsResponse tFileList(QueryRequest request, HttpServletRequest req, TFile tFile) {
        Enumeration enu=req.getParameterNames();
        HashMap<String,String> map=new HashMap<String,String>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }
        Map<String, Object> dataTable = getDataTable(this.tFileService.findTFileDetail(request, map));
        return new FebsResponse().success().data(dataTable);
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "file/add")
    public String goTFileAdd() {
        return FebsUtil.view("tFile/tFileAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "file/update/{id}")
    public String goTFileUpdate(@PathVariable String id, Model model) {
        TFile obj= tFileService.getById(id);
        model.addAttribute("obj",obj);
        return FebsUtil.view("tFile/tFileUpdate");
    }

    @ControllerEndpoint(operation = "新增TFile", exceptionMessage = "新增TFile失败")
    @PostMapping("tFile")
    @ResponseBody
    public FebsResponse addTFile(@Valid TFile tFile) {
        this.tFileService.createTFile(tFile);
        return new FebsResponse().success();
    }

    @GetMapping("file/delete/{objIds}")
    @ControllerEndpoint(operation = "删除", exceptionMessage = "删除失败")
    @ResponseBody
    public FebsResponse deleteTFile( @PathVariable String objIds) {
        String[] ids = objIds.split(StringPool.COMMA);
        this.tFileService.deleteTFile(ids);
        return new FebsResponse().success();
    }

    @ControllerEndpoint(operation = "修改TFile", exceptionMessage = "修改TFile失败")
    @PostMapping("file/update")
    @ResponseBody
    public FebsResponse updateTFile(TFile tFile) {
        this.tFileService.updateTFile(tFile);
        return new FebsResponse().success();
    }

    @PostMapping(value = "file/fileUpload")
    @ResponseBody
    public void fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request,HttpServletResponse response) throws IOException {
        StringBuffer sb=new StringBuffer();
        String msg="上传成功";
        String src="http://localhost/tFile/preFile/";
        Integer code=0;
        if (file.isEmpty()) {
            System.out.println("文件为空");
            code=1;
            msg="上传失败";
        }
        TFile tfile=new TFile();
        String fileName = file.getOriginalFilename();  // 文件名
        tfile.setRealName(new String(fileName.getBytes("UTF-8"),"UTF-8"));
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D://touch_file//"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //判断文件类型，调用工具类转化成pdf
        if(suffixName.equalsIgnoreCase(".doc") || suffixName.equalsIgnoreCase(".docx")){
            boolean b = ConvertUtil.word2Pdf(fileName, "D://touch_file//", "D://touch_file//");
            fileName = b?fileName.substring(0,fileName.lastIndexOf("."))+ ".pdf" : fileName;
        }
        tfile.setFileName(fileName);
        tfile.setFileType(suffixName);
        tfile.setCreateTime(new Date());
        tfile.setFilePath(filePath+fileName);
        this.tFileService.createTFile(tfile);
        sb.append("{");

        sb.append("\"code\":"+code);
        sb.append(",");

        sb.append("\"msg\":\""+msg+"\"");
        sb.append(",");

        sb.append("\"data\":{");
        sb.append("\"src\":\""+src+"\"");
        sb.append(",\"fileName\":\""+tfile.getFileName()+"\"");
        sb.append(",\"filePath\":\""+tfile.getFilePath()+"\"");
        sb.append(",\"realName\":\""+tfile.getRealName()+"\"");
        sb.append(",\"fileId\":\""+tfile.getId()+"\"");
        sb.append("}");






        sb.append("}");
        System.out.println(sb.toString());
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(sb.toString());
        //return new FebsResponse().success().data(tfile);
    }

    /**
     * 预览图片
     *
     * @throws IOException
     * @throws Exception
     */
    @GetMapping("file/preFile/{id}")
    public void prePhoto(@PathVariable String id, HttpServletResponse response) throws IOException {
        MenuItemFile menuItemFile = this.itemFileService.getById(id);
        //TFile file=this.tFileService.getById(id);
        if(menuItemFile!=null){
            String filePath = menuItemFile.getFilePath();
        }
        String filePath = menuItemFile.getFilePath();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        OutputStream os = null;
        InputStream is = null;
        is = new FileInputStream(filePath);
        bis = new BufferedInputStream(is);
        os = response.getOutputStream();
        bos = new BufferedOutputStream(os);
        int byteRead = 0;
        byte[] buffer = new byte[5 * 1024];
        while ((byteRead = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, byteRead);
        }
        bos.close();
        bis.close();
        os.close();
        is.close();
    }
}
